package com.heima.wemedia.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.common.constants.message.NewsAutoScanConstants;
import com.heima.common.constants.message.NewsUpOrDownConstants;
import com.heima.common.constants.message.PublishArticleConstants;
import com.heima.common.constants.wemedia.WemediaConstants;
import com.heima.common.exception.CustException;
import com.heima.model.common.dtos.PageResponseResult;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.threadlocal.WmThreadLocalUtils;
import com.heima.model.wemedia.dtos.NewsAuthDTO;
import com.heima.model.wemedia.dtos.WmNewsDTO;
import com.heima.model.wemedia.dtos.WmNewsPageReqDTO;
import com.heima.model.wemedia.pojos.WmMaterial;
import com.heima.model.wemedia.pojos.WmNews;
import com.heima.model.wemedia.pojos.WmNewsMaterial;
import com.heima.model.wemedia.pojos.WmUser;
import com.heima.model.wemedia.vos.WmNewsVO;
import com.heima.wemedia.mapper.WmMaterialMapper;
import com.heima.wemedia.mapper.WmNewsMapper;
import com.heima.wemedia.mapper.WmNewsMaterialMapper;
import com.heima.wemedia.mapper.WmUserMapper;
import com.heima.wemedia.service.WmNewsService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.amqp.AmqpException;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessagePostProcessor;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import javax.swing.*;
import javax.swing.undo.CannotUndoException;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
@Slf4j
public class WmNewsServiceImpl extends ServiceImpl<WmNewsMapper, WmNews> implements WmNewsService {

    @Value("${file.oss.web-site}")
    private String weSite;
    //依赖注入
    @Autowired
    private WmNewsMaterialMapper wmNewsMaterialMapper;

    @Autowired
    private WmMaterialMapper wmMaterialMapper;

    /**
     * 自媒体文章列表查询
     * @param dto
     * @return
     */
    @Override
    public ResponseResult findlist(WmNewsPageReqDTO dto) {
        //1.参数校验
        if (dto==null){
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID,"参数无效");
        }
        //2.执行分页查询
        Page<WmNews> dtoPage = new Page<>(dto.getPage(), dto.getSize());
        LambdaQueryWrapper<WmNews> wrapper = Wrappers.<WmNews>lambdaQuery();
        //2.如果有文章标题，按照文章标题模糊查询
        if (StringUtils.isNotBlank(dto.getKeyword())){
           wrapper.like(WmNews::getTitle,dto.getKeyword());
        }
        //3.如果有频道信息，按照频道ID查询
        if (dto.getChannelId()!=null){
            wrapper.eq(WmNews::getChannelId,dto.getChannelId());
        }
        //4.如果有文章状态，按照状态信息查询
       if (dto.getStatus()!=null){
           wrapper.eq(WmNews::getStatus,dto.getStatus());
       }
        //5.如果开始时间，结束时间不为空按照时间区间查询
        if (dto.getBeginPubDate()!=null && dto.getEndPubDate()!=null){
            wrapper.between(WmNews::getPublishTime,dto.getBeginPubDate(),dto.getEndPubDate());
        }
        //6.按照登录用户ID去查询
        //6.1查询登录的用户
        Integer userid = WmThreadLocalUtils.getUser().getId();
        if (userid!=null){
           wrapper.eq(WmNews::getUserId,userid);
        }
        //7.按照创建时间降序
        wrapper.orderByDesc(WmNews::getPublishTime);
        //8.将查询的结果封装到分页 查询中
        IPage<WmNews> result = this.page(dtoPage, wrapper);
        //8.分页查询，返回结果设置host  地址 为图片访问前缀
        PageResponseResult pageResponseResult = new PageResponseResult(dto.getPage(), dto.getSize(), result.getTotal(), result.getRecords());
        pageResponseResult.setHost(weSite);
        return pageResponseResult;
    }

    /**
     * 自媒体文章的发布，修改，保存草稿
     * @param dto
     * @return
     */
    @Autowired
    private RabbitTemplate rabbitTemplate;
    @Override
    public ResponseResult submitnews(WmNewsDTO dto) {
        //1.将前端传递来的dto数据封装到WmNews对象中
        WmNews wmNews = getWeNews(dto);
        //3.保存或修改文章
        saveOrUpdateNews(wmNews);
        //4.保存文章和素材的关联关系
        //如果当前文章是草稿，就不用保存关联关系
        if (WemediaConstants.WM_NEWS_DRAFT_STATUS.equals(dto.getStatus())){
            return ResponseResult.okResult();
        }
        //4.1从文章内容中抽取出所有的素材路径
        List<String> materialurl = parseContentImages(wmNews.getContent());
        //4.2保存文章内容所引用的素材关联关系
        if (!CollectionUtils.isEmpty(materialurl)){
            saveRelativeInfo(materialurl,wmNews.getId(),WemediaConstants.WM_CONTENT_REFERENCE);
        }
        //4.3保存文章封面所引用的素材关联关系
        saveRelativeInfoForCover(dto,materialurl,wmNews);
        //5.TODO 自动审核文章

        //  发消息   自动审核文章消息
        rabbitTemplate.convertAndSend(NewsAutoScanConstants.WM_NEWS_AUTO_SCAN_QUEUE,wmNews.getId());
        log.info("成功发送文章自动审核消息，当前待审核的文章id==>{}",wmNews.getId());
        return ResponseResult.okResult();
    }

    /**
     * 根据id查询文章
     * @param id
     * @return
     */
    @Override
    public ResponseResult findById(Integer id) {
        //1.参数检验
        if (id==null){
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID,"参数无效");
        }
        //2.根据id查询进行查询
        WmNews wmNews = this.getById(id);
        if (wmNews==null){
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST,"文章不存在");
        }
        //3.返回结果
        ResponseResult result = ResponseResult.okResult(wmNews);
        result.setHost(weSite);
        return result;
    }

    /**
     * 根据id删除文章
     * @param id
     * @return
     */
    @Override
    public ResponseResult delById(Integer id) {
        //1.参数检验
        if (id==null){
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID,"参数不存在");
        }
        //根据id获取文章的信息
        WmNews wmNews = this.getById(id);
        if (wmNews==null){
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST,"文章不存在");
        }
        //2.判断文章的状态，如果是9上架且已发布1，就不能删除
        if (WemediaConstants.WM_NEWS_PUBLISH_STATUS.equals(wmNews.getStatus()) && wmNews.getEnable().equals(WemediaConstants.WM_NEWS_UP)){
            CustException.cust(AppHttpCodeEnum.DATA_NOT_ALLOW,"文章被引用，不能被删除");
        }
        //3.执行删除，需要先删除素材与文章关联关系
        LambdaQueryWrapper<WmNewsMaterial> queryWrapper = Wrappers.<WmNewsMaterial>lambdaQuery().eq(WmNewsMaterial::getNewsId, wmNews.getId());
        wmNewsMaterialMapper.delete(queryWrapper);
        //4.删除文章
        this.removeById(wmNews.getId());
        //5.返回结果
        return ResponseResult.okResult();
    }

    /**
     * 文章上下架
     * @param dto
     * @return
     */
    @Override
    public ResponseResult downOrUp(WmNewsDTO dto) {
        //1.参数校验
        if (dto==null || dto.getId()==null){
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID,"参数无效");
        }
        //获取文章上下架状态
        Short enable = dto.getEnable();
        if (enable==null || (!WemediaConstants.WM_NEWS_UP.equals(enable) && !WemediaConstants.WM_NEWS_DOWN.equals(enable))){
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST,"文章上架下架出错");
        }
        //2.获取到文章
        WmNews wmNews = this.getById(dto.getId());
        if (wmNews==null){
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST,"文章不存在");
        }
        //3.查看文章是否已经发布
//            if (!WemediaConstants.WM_NEWS_PUBLISH_STATUS.equals(wmNews.getStatus())){
//                CustException.cust(AppHttpCodeEnum.PARAM_INVALID,"文章还未发布");
//            }
        if (!wmNews.getStatus().equals(WmNews.Status.PUBLISHED.getCode())){
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID,"文章未发布，不能上下架操作");
        }
        //只有已发布的文章才可以上下架，修改状态
        //update  XX from 表名 set  修改字段  where id =?
        //4.修改文章状态，同步到app端（后期做）TODO
        update(Wrappers.<WmNews>lambdaUpdate().eq(WmNews::getId,dto.getId())
                .set(WmNews::getEnable,dto.getEnable()));

        if (WemediaConstants.WM_NEWS_UP.equals(enable)){
            // 发送上架消息
            rabbitTemplate.convertAndSend(
                    //交换机
                    NewsUpOrDownConstants.NEWS_UP_OR_DOWN_EXCHANGE,
                    //路由
                    NewsUpOrDownConstants.NEWS_UP_ROUTE_KEY,
                    //发送内容
                    wmNews.getArticleId()
            );
            log.info("成功发送文章上架消息，消息内容是 {}",wmNews.getArticleId());
        }else {
            //发送下架消息
            rabbitTemplate.convertAndSend(
                    //交换机
                    NewsUpOrDownConstants.NEWS_UP_OR_DOWN_EXCHANGE,
                    //路由
                    NewsUpOrDownConstants.NEWS_DOWN_ROUTE_KEY,
                    //发送内容
                    wmNews.getArticleId()
            );
            log.info("成功发送文章下架消息，消息内容是{}",wmNews.getArticleId());
        }
            //返回结果
        return ResponseResult.okResult();
        }

    /**
     * 保存文章封面所引用的素材关联关系
     * @param dto
     * @param materialurl
     * @param wmNews
     */
    private void saveRelativeInfoForCover(WmNewsDTO dto, List<String> materialurl, WmNews wmNews) {
        //1.获取前端生成的素材封面
        List<String> images = dto.getImages();
        //2.如果dto.getType == -1 需要自动生成封面
        if (WemediaConstants.WM_NEWS_TYPE_AUTO.equals(dto.getType())){
            int size=materialurl==null ? 0:materialurl.size();
            if (size>0 && size<2){
                //单图模式
               images = materialurl.stream().limit(1).collect(Collectors.toList());
               wmNews.setType(WemediaConstants.WM_NEWS_SINGLE_IMAGE);
            }else if (size>2){
                //多图模式
                images=materialurl.stream().limit(3).collect(Collectors.toList());
                wmNews.setType(WemediaConstants.WM_NEWS_MANY_IMAGE);
            }else {
                //无图模式
                wmNews.setType(WemediaConstants.WM_NEWS_NONE_IMAGE);
            }
            wmNews.setImages(imagesToStr(images));
            this.updateById(wmNews);
            // 保存封面 和 素材关联关系
            if (!CollectionUtils.isEmpty(images)){
                //再一次替换前缀路径
                images=images.stream().map(url->url.replaceAll(weSite,"")).collect(Collectors.toList());
                saveRelativeInfo(images,wmNews.getId(),WemediaConstants.WM_IMAGE_REFERENCE);//文章被引用
            }
        }
    }

    /**
     * 保存文章内容所引用的素材关联关系
     * @param material
     * @param id
     * @param type
     */
    private void saveRelativeInfo(List<String> material, Integer id, Short type) {
        // 1. 先根据素材路径列表 和 当前登陆用户id  查询出 素材id集合
        List<Integer> materiallist = wmMaterialMapper.selectRelationsIds(material, WmThreadLocalUtils.getUser().getId());
        // 2. 判断传入路径的数量 和  素材id的素材是否一致 ，如果不一致说明素材缺失
        if (material.size()!=materiallist.size()){
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID,"素材缺失");
        }
        // 3. 将素材id 文章id 引用类型 插入到关联表中
        wmNewsMaterialMapper.saveRelations(materiallist,id,type);
    }

    /**
     * 从文章内容中抽取出所有的素材路径
     * 去除前缀
     * 去除重复
     * 返回路径集合
     * @param content
     * @return
     */
    private List<String> parseContentImages(String content) {
        List<Map> maps = JSON.parseArray(content, Map.class);
        //获取流
      return  maps.stream()
                //过滤操作
                .filter(m->WemediaConstants.WM_NEWS_TYPE_IMAGE.equals(m.get("type")))
                //获取素材的完成url
                .map(m->String.valueOf(m.get("value")))
                //将前缀的路径替换掉
                .map(url->url.replaceAll(weSite,""))
                //去除重复
                .distinct()
                //收集到集合
                .collect(Collectors.toList());
    }

    /**
     * 保存或者修改文章
     * @param wmNews
     */
    private void saveOrUpdateNews(WmNews wmNews) {
        //1.判断文章是否存在
        //文章不存在
        if (wmNews.getId()==null){
            //保存文章
            this.save(wmNews);
        }
        //如果文章存在
        if (wmNews.getId()!=null){
            //修改文章,先删除文件的素材的关联关系
            wmNewsMaterialMapper.delete(Wrappers.<WmNewsMaterial>lambdaQuery().eq(WmNewsMaterial::getNewsId,wmNews.getId()));
            //再保存文章
            this.updateById(wmNews);
        }
    }

    /**
     * 将dto封装到WmNews对象中
     * @param dto
     * @return
     */
    private WmNews getWeNews(WmNewsDTO dto) {
        //1.参数校验
        if (StringUtils.isBlank(dto.getContent()) || StringUtils.isBlank(dto.getTitle())){
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID,"文章内容或者标题不能为空");
        }
        //1.1判断当前是否有用户
        WmUser user = WmThreadLocalUtils.getUser();
        if (user==null){
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST,"用户不存在");
        }

        WmNews wmNews = new WmNews();
        BeanUtils.copyProperties(dto,wmNews);
        //判断文章类型是否为-1，如果是-1就赋予默认值
        if (WemediaConstants.WM_NEWS_TYPE_AUTO.equals(dto.getType())){
            wmNews.setType(null);
        }
        //images是一个集合
        List<String> images = dto.getImages();
        //将集合转为一个字符串
        wmNews.setImages(imagesToStr(images));
        //设置登录用户id
        wmNews.setUserId(user.getId());
        wmNews.setCreatedTime(new Date());
        wmNews.setSubmitedTime(new Date());
        //默认上架状态
        wmNews.setEnable(WemediaConstants.WM_NEWS_UP);
        return wmNews;
    }

    /**
     * 集合转为字符串
     * @param images
     * @return
     */
    private String imagesToStr(List<String> images) {
        if (CollectionUtils.isEmpty(images)){
            return null;
        }
        //获取流对象
      return images.stream()
                //将wesite部分替换为空字符串
                .map(url->url.replaceAll(weSite,""))
                //将集合中的路径用逗号分割开
                .collect(Collectors.joining(","));
    }

    /**
     * 查询文章列表
     * @param dto
     * @return
     */

    @Autowired
    private WmNewsMapper wmNewsMapper;

    @Override
    public ResponseResult findlists(NewsAuthDTO dto) {
        //1.参数校验
        if (dto==null){
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID,"参数无效");
        }
        dto.checkParam();
        //2.分页查询
       //当前页
        Integer currentPage = dto.getPage();
        //设置起始页 当前页码-1再乘以每页条数
        dto.setPage((dto.getPage()-1)*dto.getSize());
        //设置文章标题
        if (StringUtils.isNotBlank(dto.getTitle())){
            //  concat(%,?,%)
            dto.setTitle("%"+dto.getTitle()+"%");
        }

        //3.执行定义的分页方法
        List<WmNewsVO> listAndPage = wmNewsMapper.findListAndPage(dto);
        //统计条数
        long listCount = wmNewsMapper.findListCount(dto);
        //4.返回结果
        PageResponseResult responseResult = new PageResponseResult(dto.getPage(), dto.getSize(), listCount, listAndPage);
        responseResult.setHost(weSite);
        return responseResult;
    }

    /**
     * 根据id查询文章详情
     * @param id
     * @return
     */
    //依赖注入
    @Autowired
    private WmUserMapper wmUserMapper;
    @Override
    public ResponseResult findWmNewsVo(Integer id) {
        //1.参数校验
        if (id==null){
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID,"参数无效");
        }
        //2.根据id获取文章信息
        WmNews wmNews = this.getById(id);
        //判断文章是否存在
        if (wmNews==null){
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST,"文章不存在");
        }
        //3.查询作者
        WmUser wmUser=null;
        if (wmNews.getUserId()!=null){
            wmUser=wmUserMapper.selectById(wmNews.getUserId());
        }
        //4.封装vo信息返回
        WmNewsVO wmNewsVO = new WmNewsVO();
        BeanUtils.copyProperties(wmNews,wmNewsVO);
        if (wmUser!=null){
            wmNewsVO.setAuthorName(wmUser.getName());
        }
        //5.返回封装结果
        ResponseResult result = ResponseResult.okResult(wmNewsVO);
        result.setHost(weSite);
        return result;
    }

    /**
     * 文章审核通过或者失败
     * @param status  2  审核失败  4 审核成功
     * @param dto
     * @return
     */
    @Override
    public ResponseResult updateStatus(Short status, NewsAuthDTO dto) {
        //1.参数校验
        if (dto==null || dto.getId()==null){
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID,"参数无效");
        }
        //2.查询文章
        WmNews wmNews = this.getById(dto.getId());
        if (wmNews==null){
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST,"文章不存在");
        }
        //3.获取文章状态
        Short wmNewsStatus = wmNews.getStatus();
        //4.判断文章状态是否为9，已发布状态
        if (wmNewsStatus.equals(WmNews.Status.PUBLISHED.getCode())){
            CustException.cust(AppHttpCodeEnum.DATA_EXIST,"文章已经发布");
        }
        //5.修改文章状态
        wmNews.setStatus(status);
        if (StringUtils.isNotBlank(dto.getMsg())){
            wmNews.setReason(dto.getMsg());
        }
        updateById(wmNews);
        // TODO 通知定时发布文章
        //6.人工审核通过之后，定时发布文章
        //6.1计算文章发布时间
        long pushTime = wmNews.getPublishTime().getTime();
        //6.2计算当前时间
        long nowTime = System.currentTimeMillis();
        //6.3计算延迟时间
        long lateTime=pushTime-nowTime;
        //6.4发送消息，并设置延迟时间
        rabbitTemplate.convertAndSend(
                //交换机
                PublishArticleConstants.DELAY_DIRECT_EXCHANGE,
                //队列
                PublishArticleConstants.PUBLISH_ARTICLE_QUEUE,
                //发送的内容
                wmNews.getId(),
                new MessagePostProcessor() {
                    /**
                     * 消息的后置处理器，可以对消息属性进行设置
                     * @param message
                     * @return
                     * @throws AmqpException
                     */
                    @Override
                    public Message postProcessMessage(Message message) throws AmqpException {
                        //设置 x-delay 延迟时间
                        //延迟时间小于等于0直接发送
                        message.getMessageProperties().setHeader("x-delay",lateTime<=0?0:lateTime);
                        return message;
                    }
                }
        );
        log.info("成功发送延时发布文章消息   文章id:{}  延迟时间: {}",wmNews.getId(),lateTime);
        return ResponseResult.okResult();
    }

}
